package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryService;
import com.leyou.item.service.SkuService;
import com.leyou.item.service.SpuService;
import org.bouncycastle.asn1.esf.SPuri;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements SpuService {

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;


    @Override
    public PageDTO<SpuDTO> pageQuery(Integer page, Integer rows, Long id, Long bid, Long cid, Boolean saleable) {

        Page<Spu> spuPage = new Page<>(page,rows);
        page(spuPage,new QueryWrapper<Spu>()
        .eq(id!=null,"id",id)
        .eq(null!=bid,"brand_id",bid)
        .eq(null!=cid,"cid3",cid)
        .eq(null!=saleable,"saleable",saleable));

        List<SpuDTO> spuDTOS = SpuDTO.convertEntityList(spuPage.getRecords());

        spuDTOS.forEach(spuDTO -> {
            //根据品牌id查询对应的品牌对象，获取其name
            spuDTO.setBrandName(this.brandService.getById(spuDTO.getBrandId()).getName());


            //根据分类id的集合查询对应的分类的集合
            String names = this.categoryService
                    .queryCategoryByIds(spuDTO.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("/"));

            //TODO 考虑优化问题，分类及品牌查询时候缓存问题
            spuDTO.setCategoryName(names);
        });

        return new PageDTO<>(spuPage.getTotal(),spuPage.getPages(),spuDTOS);
    }

    @Autowired
    private SkuService skuService;


    @Override
    @Transactional
    public void modifySaleable(Long spuId, Boolean saleable) {
        //todo 修改spu

        Spu spu = new Spu();
        spu.setId(spuId);

        spu.setSaleable(saleable);

        //update tb_spu set saleable = true where id = 2
        updateById(spu);

        //todo 修改sku

        Sku sku = new Sku();
        sku.setSaleable(saleable);

        //update tb_sku set saleable = true where spu_id = 2
        this.skuService.update(sku,new QueryWrapper<Sku>().eq("spu_id",spuId));
    }
}
